import React, {ChangeEvent, useContext, useEffect, useState} from "react";
import "./styles/UserPage.css";
import {getImageById} from "../../http/imageApi";
import handleImageNotLoaded from "../../functions/handleImageNotLoaded";
import {getUserById} from "../../http/userApi";
import UserInfo from "../../models/UserInfo";
import UserUpdateModal from "./components/UserUpdateModal/UserUpdateModal";
import {UserContext} from "../../index";
import GetUserTokensDto from "../../utils/dto/token/getUserTokensDto";
import {getUserTokens} from "../../http/tokenApi";
import Token from "../../models/Token";
import {getPaginationRange} from "../../functions/getPaginationRange";
import {useLocation, useNavigate} from "react-router-dom";
import {getChainById} from "../../http/chainApi";
import Chain from "../../models/Chain";
import {formatDate} from "../../functions/formatDate";
import routeNames from "../../utils/routeNames";


const UserPage = () => {
    const userStore = useContext(UserContext);
    const [reloadTrigger, setReloadTrigger] = useState(false);
    const [user, setUser] = useState<UserInfo | null>();
    const [isModalOpen, setIsModalOpen] = useState(false);
    const location = useLocation();
    const userInfoId = location.state ? location.state : userStore.user.userInfoId;
    const [pageNumber, setPageNumber] = useState(1);
    const [pageSize] = useState(15);
    const [filter, setFilter] = useState(localStorage.getItem('UserPageSearchValue') ?? "");
    const [searchTrigger, setSearchTrigger] = useState(false);
    const [totalPages, setTotalPages] = useState(1);
    const [tokens, setTokens] = useState<{ token: Token; chain: Chain }[]>([]);
    const navigate = useNavigate()

    const fetchTokens = async () => {
        let dto = new GetUserTokensDto(pageNumber, pageSize, filter, userInfoId);
        const response = await getUserTokens(dto);
        if (response.status === 200) {
            const tokenPromises = response.data.tokens.map(async (token: Token) => {
                const chainResponse = await getChainById(token.chainId);
                return {token, chain: chainResponse.data};
            });
            const tokensWithChains = await Promise.all(tokenPromises);
            setTokens(tokensWithChains);
            let newTotalPages = Math.ceil(response.data.count / pageSize);
            setTotalPages(newTotalPages === 0 ? 1 : newTotalPages);
        } else {
            console.error(response.statusText);
        }
    };

    useEffect(() => {
        if (userInfoId) getUserById(userInfoId).then(setUser);
        else getUserById(userStore.user.userInfoId).then(setUser);
    }, []);

    useEffect(() => {
        fetchTokens().catch(error => console.error(error));
    }, [reloadTrigger, pageNumber, searchTrigger]);

    if (!user) {
        return null;
    }

    const handleEditProfile = () => {
        setIsModalOpen(true);
    };

    const handleModalClose = () => {
        setIsModalOpen(false);
        setReloadTrigger((prevState) => !prevState);
    };

    const handlePageChange = (newPageNumber: number) => {
        setPageNumber(newPageNumber);
    };

    const handleSearchChange = (e: ChangeEvent<HTMLInputElement>) => {
        setFilter(e.target.value);
        localStorage.setItem('UserPageSearchValue', e.target.value)
    };

    const handleSearchClick = () => {
        setTokens([]);
        setSearchTrigger(prevState => !prevState);
        setPageNumber(1);
    };

    return (
        <div className="user-page-container">
            <div className="user-info">
                <div className="user-avatar">
                    <img src={getImageById(user.imageId)} onError={handleImageNotLoaded} alt="Your avatar"/>
                </div>
                <div className="user-details">
                    <h2>{user.userName}</h2>
                    <p>{user.firstName} {user.lastName} {user.patronymic}</p>
                    <p>{user.countryName}</p>
                    <button onClick={handleEditProfile}>Изменить данные о себе</button>
                </div>
            </div>
            <div className="tokens-header">
                <h2 className="tokens-title">Tokens</h2>
                <form className="col-lg-7 breadcrumbs-form md-pt-30" onSubmit={(e) => {
                    e.preventDefault();
                    fetchTokens().catch(error => console.error(error));
                }}>
                    <input type="text" id="Search" name="search" value={filter}
                           onChange={(e) => handleSearchChange(e)}
                           placeholder="Search by name"/>
                    <span className="submit" onClick={handleSearchClick}><i
                        className="icon-search"></i><input type="submit"/></span>
                </form>
            </div>
            <ul className="tokens-list">
                {tokens.map(({token, chain}) => (
                    chain.isFound && (
                        <li key={token.id} className="token-item"
                            onClick={() => navigate(routeNames.PROJECT_DETAILS_PAGE, {state: {tokenId: token.id}})}>
                            <img src={getImageById(token.imageId)} onError={handleImageNotLoaded} alt={token.name}/>
                            <div className="token-details">
                                <h4>{token.name}</h4>
                                <p>Price: {token.tokenPrice} BUSD</p>
                                <p>Token Symbol: {token.tokenSymbol.toUpperCase()}</p>
                                <p>Chain: <img src={getImageById(chain.imageId)} alt={chain.name} onError={handleImageNotLoaded}/> {chain.name}</p>
                                <p>Created: {formatDate(token.createdDate)}</p>
                                <p>Targeted Raise: {token.targetedRaise}</p>
                                <p>Total Raise: {token.totalRaise}</p>
                            </div>
                        </li>
                    )
                ))}
            </ul>
            <div className="gamfi-navigation text-center mt-40">
                <ul>
                    <li>
                        <a
                            onClick={() => pageNumber > 1 && handlePageChange(pageNumber - 1)}
                            className={pageNumber === 1 ? "disabled" : ""}
                            style={{cursor: pageNumber === 1 ? "default" : "pointer"}}
                        >
                            <i className="icon-Vector"></i>
                        </a>
                    </li>
                    {getPaginationRange(pageNumber, pageSize, totalPages).map((page, index) => (
                        <li key={index}>
                            <a
                                style={{cursor: page === '...' ? 'default' : 'pointer'}}
                                className={pageNumber === page ? "active" : ""}
                                onClick={() => typeof page === 'number' && handlePageChange(page)}
                            >
                                {page}
                            </a>
                        </li>
                    ))}
                    <li>
                        <a
                            onClick={() => pageNumber < totalPages && handlePageChange(pageNumber + 1)}
                            className={pageNumber === totalPages ? "disabled" : ""}
                            style={{cursor: pageNumber === totalPages ? "default" : "pointer"}}
                        >
                            <i className="icon-arrow_right"></i>
                        </a>
                    </li>
                </ul>
            </div>
            {isModalOpen && <UserUpdateModal user={user} onClose={handleModalClose}/>}
        </div>
    );
};

export default UserPage;
